class FriendManager
	def initialize(id)
		@id=id.to_s
	end
	def one_of_friends?(friend_id)
		if @friends_ids.nil?
		    require 'set'
			friends=Friend.find(:all,:conditions=>["person_id=:person_id",{:person_id=>@id}])
    		friends=[] if friends.nil?
			@friends_ids=Set.new
			friends.each{|n| @friends_ids<<n.friend_id}
		end
		@friends_ids.include?(friend_id)
	end
	def is_friend?(friend_id)
		friends=Friend.find(:first,:conditions=>["person_id=:person_id and friend_id=:friend_id",{:person_id=>@id, :friend_id=>friend_id}])
		!(friends.nil?)
	end
	def is_follower?(friend_id)
		friends=Friend.find(:first,:conditions=>["person_id=:person_id and friend_id=:friend_id",{:friend_id=>@id, :person_id=>friend_id}])
		!(friends.nil?)
	end
	def one_of_followers?(friend_id)
		if @joined_ids.nil?
		    require 'set'
		  	his_connections=UserConnection.find(:all,:conditions=>["friend_id=:friend_id",{:friend_id=>@id}])
    		his_connections=[] if his_connections.nil?
			@joined_ids=Set.new
			his_connections.each{|n| @joined_ids<<n.user_id}
		end
		@joined_ids.include?(friend_id)
	end
	def friends
		Person.find(:all,:conditions=>["id in (select friend_id from friends where friends.person_id=:person_id)",{:person_id=>@id}])
	end
	def followers
		Person.find(:all,:conditions=>["id in (select person_id from friends where friends.friend_id=:person_id)",{:person_id=>@id}])
	end
	def add_friend!(friend_id)
	  	friend=Friend.find(:first,:conditions=>["person_id=:user_id and friend_id=:friend_id",{:friend_id=>friend_id,:user_id=>@id}])
	  	if friend.nil?
	  		friend=Friend.new
	  		friend.person_id=@id
	  		friend.friend_id=friend_id
	  		friend.save
			@friends_ids=nil
	  	end
  	end
  	def remove_friend!(friend_id)
  		return if(@id.to_i==friend_id.to_i)
  	  	friend=Friend.find(:first,:conditions=>["person_id=:user_id and friend_id=:friend_id",{:friend_id=>friend_id,:user_id=>@id}])
  		unless friends.nil?
  			friend.destroy
			@joined_ids=nil
  		end
  	end
  	def remove_follower!(friend_id)
  		return if(@id.to_i==friend_id.to_i)
  	  	friend=Friend.find(:first,:conditions=>["user_id=:user_id and friend_id=:friend_id",{:friend_id=>@id,:user_id=>friend_id}])
  		unless friends.nil?
  			friend.destroy
			@joined_ids=nil
  		end
  	end
end